package com.bw.goods.service.impl;

import com.bw.common.utils.R;
import com.bw.goods.config.JwtUtil;
import com.bw.goods.config.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Random;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.common.utils.PageUtils;
import com.bw.common.utils.Query;

import com.bw.goods.dao.UserDao;
import com.bw.goods.entity.UserEntity;
import com.bw.goods.service.UserService;
import org.springframework.transaction.annotation.Transactional;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    //注册
    @Override
    public void register(UserEntity userEntity) {
        userEntity.setPassword(MD5Util.md5Code(userEntity.getPassword(),1));
        userEntity.setSalt("1a2b3c");
        userEntity.setRegisterData(new Date());
        userDao.insert(userEntity);
    }

    //登录
    @Override
    public R login(UserEntity userEntity) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(userEntity.getNickname())) {
            wrapper.eq("nickname",userEntity.getNickname());
            UserEntity entity = userDao.selectOne(wrapper);
            if(entity!=null) {
                String code = MD5Util.md5Code(userEntity.getPassword(), 1);
                if(!"".equals(code) && code.equals(entity.getPassword())) {
                    String token = jwtUtil.createJWT(entity.getNickname(), entity.getNickname(), "admin");
                    entity.setLastLoginData(new Date());
//                    entity.setLoginCount(entity.getLoginCount()+1);
                    userDao.updateById(entity);
                    entity.setPassword("");
                    return R.ok().put("token",token).put("entity",entity);
                }else {
                    return R.error("密码错误");
                }
            }else {
                return R.error("该用户名未注册");
            }
        }else {
            return R.error("信息不完整");
        }
    }

}